package xx.iverson.video_manage.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author 86131
 */
@Controller
public class VideoController {

    // 现有的视频流服务方法保持不变
    @GetMapping("/videos/{fileName:.+}")
    public ResponseEntity<Resource> serveVideo(@PathVariable String fileName) throws MalformedURLException {
        Path filePath = Paths.get("D:/video_manage/videos/", fileName);
        Resource resource = new UrlResource(filePath.toUri());

        if (resource.exists()) {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.parseMediaType("video/mp4").toString())
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 新增的方法：处理视频播放页面请求
    @GetMapping("/playVideo")
    public String playVideo(@RequestParam("videoUrl") String videoUrl, Model model) {
        try {
            // 对 URL 进行解码
            String decodedVideoUrl = java.net.URLDecoder.decode(videoUrl, "UTF-8");
            model.addAttribute("videoUrl", "/videos/" + decodedVideoUrl);
            // 如果有视频标题等其他信息也可以在这里设置
            model.addAttribute("videoTitle", videoUrl);
        } catch (Exception e) {
            // 处理解码错误或其他异常情况
            e.printStackTrace();
            return "error";
        }
        return "video-player";
    }
}